#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/can.h>
#include <linux/can/raw.h>

int main(void) {
    int s; // 套接字文件描述符
    struct sockaddr_can addr;
    struct can_frame frame;
    struct ifreq ifr;

    // 创建套接字
    s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
    if (s < 0) {
        perror("Socket");
        return 1;
    }

    strcpy(ifr.ifr_name, "can0");
    ioctl(s, SIOCGIFINDEX, &ifr);

    memset(&addr, 0, sizeof(addr));
    addr.can_family = AF_CAN;
    addr.can_ifindex = ifr.ifr_ifindex;

    // 将套接字绑定到CAN接口
    if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
        perror("Bind");
        return 1;
    }

    // 准备CAN帧
    frame.can_id = 0x123; // CAN ID
    frame.can_dlc = 2; // 数据长度
    frame.data[0] = 0x11; // 数据
    frame.data[1] = 0x22;

    // 发送CAN帧
    if (write(s, &frame, sizeof(struct can_frame)) != sizeof(struct can_frame)) {
        perror("Write");
        return 1;
    }

    printf("CAN frame sent\n");

    close(s);
    return 0;
}